//
//  SSOauthModel.swift
//  weibo
//
//  Created by 邵帅 on 16/6/24.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//


import UIKit

class SSOauthModel: NSObject {
    
    static let shareInstance: SSOauthModel = SSOauthModel()
    
    // 拿到模型，进行是否已登录的逻辑判断
    var userModel : SSUserModel?
    // 定义了单例，可以使用私有方法
    private override init() {
        
        super.init()
        
        userModel = SSUserModel.readModel()
    }
    
    // 判断token是否有值
    var access_token: String? {
        
        return userModel?.access_token
    }
    
    // 根据token是否有值来判断是否已登录
    var isLogin: Bool {
        
        return access_token == nil ? false : true
    }
    
    // 通过code获取token和id
    func loadToken(code : String, success : ()->(), falsed : ()->()) {
    
    let param = [
    
    "client_id" : AppKey,
    "client_secret" : AppSecret,
    "grant_type" : "authorization_code",
    "code" : code,
    "redirect_uri" : AppRedirectURL
    ]
    
    SSHTTPClient.shareInstance.request(.POST, URLString: "https://api.weibo.com/oauth2/access_token", parameters: param, progress: nil, success: { (_, JSON) in
    
    // JSON是AnyObject类型，需要转成字典类型
    if let userDict = JSON as? [String : AnyObject]{
    
    // 字典转模型
    let model = SSUserModel(dict: userDict)
    
    // 闭包中调用方法需要用self
    self.loadUserInfo(model, infoSuccess: success, infoFalsed: falsed)
    
    }
    
    }) { (_, error) in
    
    printLog(error)
    falsed()
    }
    
    }
    
    
    

    
    // 通过token和id的模型，获取用户信息
    private func loadUserInfo(model : SSUserModel, infoSuccess:()->(), infoFalsed:()->()) {
    
    
    guard let access_token = model.access_token, uid = model.uid else {
    
    return
    }
    
    // 字典里不能填可选项，需要上面那步
    let param = [
    
    "access_token" :  access_token,
    "uid" : uid
    ]
    
    SSHTTPClient.shareInstance.request(.GET, URLString: "https://api.weibo.com/2/users/show.json", parameters: param, progress: nil, success: { (_, JSON) in
    
    guard let infoDict = JSON as? [String : AnyObject] else {
    
    return
    }
    
    // 为模型赋值
    model.screen_name = infoDict["screen_name"] as? String
    model.profile_image_url = infoDict["profile_image_url"] as? String
    
    // 请求成功后为模型赋值
    self.userModel = model
        
    model.saveModel()
    
    infoSuccess()
    
    }) { (_, error) in
    
    printLog(error)
    infoFalsed()
    }
    
    }
    
    
}
